package com.huatai.exchange.deal;

import com.alibaba.fastjson.JSON;
import com.faneui.common.exception.BusinessException;
import com.faneui.common.utils.CloseUtils;
import com.faneui.integration.http.HttpClientUtils;
import com.google.common.collect.Maps;
import com.huatai.exchange.dal.model.ExcDataFileInfo;
import com.huatai.exchange.dal.model.ExcExchangeDataFile;
import com.huatai.exchange.facade.FileSourceContents;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service("fileCreateHttpDealService")
public class FileCreateHttpDealServiceImpl extends AbstractFileCreateDealServiceImpl implements FileCreateDealService {

    @Override
    public void downloadCreateFile(StringBuffer fileNames, StringBuffer filePaths, ExcExchangeDataFile exchangeDateFile, ExcDataFileInfo dataFileInfo, Map<String, Object> resvMap) throws BusinessException {
        OutputStream os = null;
        String tmpFilePath = tmpFile + UUID.randomUUID().toString();
        File f = new File(tmpFilePath);
        try {
            Map<String, Object> excDataFileMap = StringUtils.isBlank(exchangeDateFile.getProperties()) ? Maps.newHashMap() : JSON.parseObject(exchangeDateFile.getProperties(), HashMap.class);
            excDataFileMap.putAll(resvMap);// 继承上层参数


            Map<String, Object> valueMap = JSON.parseObject(dataFileInfo.getValue(), HashMap.class);
            String fileName = formatStr(dataFileInfo.getFileName(), excDataFileMap);
            String httpUrl = formatStr((String) valueMap.get(FileSourceContents.HTTP_URL), excDataFileMap);
            os = new FileOutputStream(f);
            HttpClientUtils.downLoadFile(httpUrl, Maps.newHashMap(), os);
            fileNames.append(",").append(fileName);
            String filePath = fileOperateService.uploadFile(f);
            filePaths.append(",").append(filePath);
        } catch (Exception ex) {
            BusinessException.throwBusinessException(ex);
        } finally {
            CloseUtils.safeClose(os);
            f.deleteOnExit();
        }
    }
}
